/**
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package xyz.geminiwen.skinsprite.app;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.window.service.WindowManager;
import ohos.global.systemres.ResourceTable;
import xyz.geminiwen.skinsprite.view.Skinnable;

public class SkinnableAbilitySlice extends AbilitySlice {

    private SkinnableAbility.SkinnableCallback mSkinnableCallback;
    private ComponentContainer root;

    public void setReUIComponent(int layoutRes) {
        root = (ComponentContainer) SkinnableComponentLayoutScatter.getInstance(this).parse(layoutRes, null, false);
        super.setUIContent(root);
    }

    public void setSkinnableCallback(SkinnableAbility.SkinnableCallback skinnableCallback) {
        mSkinnableCallback = skinnableCallback;
    }

    public void setDayNightMode(int nightMode) {
        if (mSkinnableCallback != null) {
            mSkinnableCallback.beforeApplyDayNight();
        }
        setColorMode(nightMode);
        applyDayNightForStatusBar();
        SkinnableComponentLayoutScatter.getInstance(this).updateProxy(this);
        Component decorView = root;
        applyDayNightForView(decorView);

        if (mSkinnableCallback != null) {
            mSkinnableCallback.onApplyDayNight();
        }
    }

    private void applyDayNightForView(Component view) {
        if (view instanceof Skinnable) {
            Skinnable skinnable = (Skinnable) view;
            if (skinnable.isSkinnable()) {
                skinnable.applyDayNight();
            }
        }
        if (view instanceof ComponentContainer) {
            ComponentContainer parent = (ComponentContainer) view;
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                applyDayNightForView(parent.getComponentAt(i));
            }
        }
    }

    private void applyDayNightForStatusBar() {
        WindowManager.getInstance().getTopWindow().ifPresent(window -> window.setStatusBarColor(getDayNightStatusColor()));
    }

    /**
     * 获取昼夜模式状态栏颜色
     *
     * @return 颜色值
     */
    protected int getDayNightStatusColor() {
        return getColor(ResourceTable.Color_id_color_statusbar_bg);
    }
}
